#!/bin/bash
#
# Start the network....
#
if [[ -n $has_usb_nic ]]; then
    echo "Please unplug your device and replug it into the usb port"
    echo -n "Please press enter key to connect [Enter]"
    read -p "$*"
    echo "Sleeping for 5 seconds to allow USB to sync back with system"
    sleep 5
fi

# Geo-Grabbing kernel parameters because the variables are probably not set yet
for var in $(cat /proc/cmdline); do
	var=$(echo "${var}" | awk -F= '{name=$1; gsub(/[+][_][+]/," ",$2); gsub(/"/,"\\\"", $2); value=$2; if (length($2) == 0 || $0 !~ /=/ || $0 ~ /nvme_core\.default_ps_max_latency_us=/) {print "";} else {printf("%s=%s", name, value)}}')
    [[ -z $var ]] && continue;
    eval "export ${var}" 2>/dev/null
done

# Enable loopback interface
echo -e "auto lo\niface lo inet loopback\n\n" > /etc/network/interfaces
/sbin/ip addr add 127.0.0.1/8 dev lo
/sbin/ip link set lo up

sleep 10

# Generated a sorted list with primary interfaces first
read p_ifaces <<< $(/sbin/ip -0 addr show | awk 'ORS=NR%2?FS:RS' | awk -F'[: ]+' 'tolower($0) ~ /link[/]?ether/ && tolower($0) ~ /'$mac'/ {print $2}' | tr '\n' ' ')
read o_ifaces <<< $(/sbin/ip -0 addr show | awk 'ORS=NR%2?FS:RS' | awk -F'[: ]+' 'tolower($0) ~ /link[/]?ether/ && tolower($0) !~ /'$mac'/ {print $2}' | tr '\n' ' ')
ifaces="$p_ifaces $o_ifaces"
for iface in $ifaces; do
    echo "Starting $iface interface and waiting for the link to come up"
    echo -e "auto $iface\niface $iface inet dhcp\n\n" >> /etc/network/interfaces
    /sbin/ip link set $iface up

    # Wait till the interface is fully up and ready (spanning tree)
    timeout=0
    linkstate=0
    until [[ $linkstate -eq 1 || $timeout -ge 35 ]]; do
        let timeout+=1
        linkstate=$(/bin/cat /sys/class/net/$iface/carrier)
        [[ $linkstate -eq 0 ]] && sleep 1 || break
    done
    [[ $linkstate -eq 0 ]] && echo "No link detected on $iface for $timeout seconds, skipping it." && continue
    for retry in $(seq 3); do
        /sbin/udhcpc -i $iface --now
        ustat="$?"
        curl -Ikfso /dev/null "${web}"/index.php --connect-timeout 5
        cstat="$?"
        # If the udhcp is okay AND we can curl our web
        # we know we have link so no need to continue on.
        # NOTE: the link to web is kind of important, just
        # exiting on dhcp request is not sufficient.
        if [[ $ustat -eq 0 && $cstat -eq 0 ]]; then
            mac_curr=$(ip link show $iface | awk '/ether/ {print tolower($2)}')
            if [[ ! -z $setmacto ]]; then
                mac_sett=$(echo "$setmacto" | awk '{print tolower($1)}')
                if [[ "x$mac_curr" != "x$mac_sett" ]]; then
                    ip link set dev $iface down
                    ip link set dev $iface address $mac_sett
                    ip link set dev $iface up
                    /sbin/udhcpc -i $iface --now
                    ustat="$?"
                    curl -Ikfso /dev/null "${web}"/index.php --connect-timeout 5
                    cstat="$?"
                    [[ $ustat -eq 0 && $cstat -eq 0 ]] && exit 0
                fi
            fi
            [[ $ustat -eq 0 && $cstat -eq 0 ]] && exit 0
        fi
        echo "Either DHCP failed or we were unable to access ${web}/index.php for connection testing."
        # Geo-If we are on the 2nd loop, lets check to see if
        # spanning tree is blocking dhcp
        if [[ $seq -eq 2 ]]; then
            echo "Waiting for Spanning Tree timeout on ${iface}..."
            sleep 27
        else
            sleep 1
        fi
    done
    echo "No DHCP response on interface $iface, skipping it."
done

# If we end up here something went wrong as we do exit the script as soon as we get an IP!
if [[ -z "$(echo $ifaces | tr -d ' ')" ]]; then  # because ifaces is constructed with a space, we must strip it
    echo "No network interfaces found, your kernel is most probably missing the correct driver!"
else
    echo "Failed to get an IP via DHCP! Tried on interface(s): $ifaces"
fi
echo "Please check your network setup and try again!"
[[ -z $isdebug ]] && sleep 60 && reboot
echo "Press enter to continue"
read -t 60
exit 1
